//
//  NSString+Helper.m
//  智能备考学习
//
//  Created by 盛超 on 2018/8/15.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "NSString+Helper.h"

#import "sys/utsname.h"

@implementation NSString (Helper)

- (NSString*)handleHtml {
    NSString *html = self;
    html = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    
    return  html;
}

/*处理在Label上展示的html文本*/
- (NSAttributedString *)showHTMLText:(CGFloat)fontsize {
    
    UILabel *label = [[UILabel alloc] init];
    NSString *string =[self stringByAppendingString:[NSString stringWithFormat:@"<style>body{word-wrap:normal|break-word; font-family: '%@';font-size:%fpx;line-height:0px;}</style>",label.font.fontName,fontsize]];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
    string = [string stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[string  dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}  documentAttributes:nil error:nil];
    
    NSMutableAttributedString *mutableAttrstring =[[NSMutableAttributedString alloc]initWithAttributedString:attrStr];
    
    return mutableAttrstring;
}

/*处理在webViews上展示的html文本*/
- (NSString*)webViewHtmlStringWithFont:(CGFloat)font {
    if (![self isEqualToString:@""] ) {
        
        NSString *string = self;
        if (self.length>=4) {
            NSString *str = [self substringWithRange:NSMakeRange(0, 3)];
            NSString *str2 = [self substringWithRange:NSMakeRange(0, 4)];
            if([str isEqualToString:@"<P>"]||[str isEqualToString:@"<p>"]) {
                string = [string stringByReplacingCharactersInRange:NSMakeRange(0, 3) withString:@""];
            } else if ([str2 isEqualToString:@"<BR>"]||[str isEqualToString:@"<br>"]) {
                string = [string stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:@""];
            }
        }
        
        UILabel *label = [[UILabel alloc] init];
        string =[string stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@';font-size:%fpx;}</style>",label.font.fontName,font]];
        string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
        string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
        
        string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
        return string;
    }
    
    return self;
}

#pragma mark - html文本处理
- (NSAttributedString *)dr_HtmlString
{
    NSData *data = [self dataUsingEncoding:NSUnicodeStringEncoding];
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:data options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    return attrStr;
}

- (NSAttributedString *)dr_HtmlStringWithFontSize:(float)fontSize
{
    NSMutableAttributedString *mutableString = self.dr_HtmlString.mutableCopy;
    
    [mutableString enumerateAttribute:(NSString *)NSFontAttributeName inRange:NSMakeRange(0, mutableString.length) options:NSAttributedStringEnumerationReverse usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        UIFont *font = (UIFont *)value;
        UIFontDescriptor *ctfFont = font.fontDescriptor;
        NSString *postScriptName = ctfFont.postscriptName;
        
        if (font)
        {
            CGFloat defaultFontSize = 12.0;//html富文本转换后默认默认大小为12.0
            [mutableString removeAttribute:NSFontAttributeName range:range];
            
            CGFloat diff = (fontSize - defaultFontSize) > 0 ? (fontSize - defaultFontSize) : 0;
            UIFont *newFont = [UIFont systemFontOfSize:font.pointSize + diff];
            
            if ([postScriptName isEqualToString:@"TimesNewRomanPS-BoldMT"]) {
                newFont = [UIFont boldSystemFontOfSize:font.pointSize + diff];
            }
            else if ([postScriptName isEqualToString:@"TimesNewRomanPS-ItalicMT"])
            {
                newFont = [UIFont italicSystemFontOfSize:font.pointSize + diff];
            }
            else if ([postScriptName isEqualToString:@"TimesNewRomanPS-BoldItalicMT"])
            {
                newFont = [UIFont fontWithName:@"Helvetica-BoldOblique" size:font.pointSize + diff];
            }
            
            [mutableString addAttribute:NSFontAttributeName value:newFont range:range];
        }
    }];
    
    [mutableString enumerateAttribute:(NSString *)NSForegroundColorAttributeName inRange:NSMakeRange(0, mutableString.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        
        CGColorRef color = (__bridge CGColorRef)(value);
        
        NSString *colorPrintString = [NSString stringWithFormat:@"%@",color];
        
        //想不到更好的比较方式，暂时这样处理
        if ([colorPrintString isEqualToString:@"kCGColorSpaceModelRGB 0 0 0 1 "]) {
            [mutableString removeAttribute:NSForegroundColorAttributeName range:range];
            
            [mutableString addAttribute:NSForegroundColorAttributeName
                                  value:[UIColor blackColor]
                                  range:range];
        }
    }];
    
    return mutableString;
}

#pragma mark - 时间
- (NSString *)transfromNormalTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:self];
    
    dateFormatter.dateFormat =@"yyyy.MM.dd";
    NSString*timeStr = [dateFormatter stringFromDate:date];
    
    return timeStr;
}

- (NSString *)transfromShortTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *date = [dateFormatter dateFromString:self];
    
    dateFormatter.dateFormat =@"yyyy.MM.dd HH:mm";
    NSString*timeStr = [dateFormatter stringFromDate:date];
    
    return timeStr;
}

- (NSString *)transfromLongTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSDate *date = [dateFormatter dateFromString:self];
    
    dateFormatter.dateFormat =@"yyyy.MM.dd HH:mm";
    NSString*timeStr = [dateFormatter stringFromDate:date];
    
    return timeStr;
}


#pragma mark - 朱凯 2018.8.22
#pragma mark - URL String Encode
- (NSString *)stringByEncodingURLFormat {
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (__bridge CFStringRef)self,
                                                              (__bridge CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}


#pragma mark - URL String Decode
- (NSString *)stringByDecodingURLFormat {
    NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}


#pragma mark - 判断字符串是否可用
- (BOOL) isStringNull {
    
    if (self == nil|| self.length <=0 || [self class] == [NSNull class]) {
        return YES;
    }
    return NO;
}


/** 获得需要的正则表达式 */
+ (NSString *)getRegexStringWithType:(ByRegexString)type {
    NSString *regex = nil;
    switch (type) {
        case EMAIL:
            regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
            break;
        case MOBILE:
            regex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
            break;
        case IDENTITY:
            regex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
            break;
        default:
            break;
    }
    
    return regex;
}
#pragma mark - 检测是否匹配正则表达式 regex
-(BOOL)isMatchPredicateWithRegex:(NSString *)regex{
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}



#pragma mark - 获得字符串的size（不能用于高度获得）根据字体大小 和 粗细
- (CGSize)getSizeOfString:(float)font{
    
    UIFont *infofont = FONT(font);
    CGSize size = [self sizeWithAttributes:@{NSFontAttributeName: infofont}];
    return size;
}
- (CGSize)getSizeOfBlodString:(float) font{
    
    UIFont *infofont = B_FONT(font);
    CGSize size = [self sizeWithAttributes:@{NSFontAttributeName: infofont}];
    return size;
}


#pragma mark - 获得字符串的rect 根据字体大小 和 展示视图的宽度
- (CGRect)getRectOfStringWithSize:(CGSize)size font:(float)font{
    
    NSDictionary *tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:font],NSFontAttributeName,nil];
    CGRect rect = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:nil];
    
    return rect;
}


/** 下面两个方法应配合使用 */
#pragma mark - 获得带属性的字体（主要为行间距和字间距）
- (NSAttributedString *)attributeString:(CGFloat)font {
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self];
    // 段落重排
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 2;// 行间距
    [attrString addAttributes:@{
                                NSKernAttributeName:@1, // 字间距
                                NSParagraphStyleAttributeName:style, // 行布局
                                NSFontAttributeName:FONT(font)
                                }
                        range:NSMakeRange(0, self.length)];
    
    return attrString;
}
#pragma mark - 获得字间距@1，行间距2，字体font的rect
- (CGRect)getRectOfAttributeStringWithSize:(CGSize)size font:(float)font {
    
    // 段落重排属性
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 2;// 行间距 数值
    NSDictionary *attrDic = @{
                              NSKernAttributeName:@1, // 字间距
                              NSFontAttributeName:FONT(font),
                              NSParagraphStyleAttributeName:style
                              };
    //修改代码
    CGRect rect = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attrDic context:nil];
    
    return rect;
}

///** 获得带表情的字符串的size */
//- (CGSize)getMixTextSizeWithWidth:(CGFloat)width line:(NSInteger)line fontSize:(CGFloat)fontSize {
//
//    UILabel *mixLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
//    mixLabel.numberOfLines = line;
//    mixLabel.font = FONT(fontSize);
//    mixLabel.mixText = self;
//    return mixLabel.mixTextSize;
//}


#pragma mark - 获得由删除线的 NSMutableAttributedString 如果需要增加其他属性，在此基础上增加
- (NSMutableAttributedString *)deleteLineAttributedStringWithColor:(UIColor *)color range:(NSRange )range {
    
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self];
    
    [attrString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:range];//删除线
    [attrString addAttribute:NSStrikethroughColorAttributeName value:color range:range];//删除线蓝色
    
    return attrString;
}




#pragma mark - 获得加密的字符串
#pragma mark -- 1:手机号（11位数字）显示前4位和后三位，其他为*
#pragma mark -- 2:身份证（18位）显示前8位和后4位，其他为*
#pragma mark -- 3:姓名（2~4位）隐藏第一位
- (NSString *)getEncryptedString {
    
    if (self.length == 11) {
        return [self stringByReplacingCharactersInRange:NSMakeRange(4, 4) withString:@"****"];
    }
    else if (self.length == 18) {
        return [self stringByReplacingCharactersInRange:NSMakeRange(8, 6) withString:@"******"];
    }
    else {
        return [self stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@"*"];
    }
}





#pragma mark - 获得手机版本
+ (NSString*)deviceVersion {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    /*
     if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
     if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
     if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
     if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
     if ([deviceString isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
     if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
     if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
     if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
     if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6Plus";
     if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
     */
    
    
    return deviceString;
}
#pragma mark - 字典转json字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

@end
